﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using Mono.WebServer;
using Netcare.Core;

namespace Netcare.Web.Host.Linux
{
    public class XspHost
    {
        public static Xsp Create(int port, string vpath, string ppath)
        {
            using (var source = new XSPWebSource(IPAddress.Any, port, false))
            {
                var server = new ApplicationServer(source);
                server.Verbose = false;
                server.SingleApplication = false;
                server.AddApplicationsFromCommandLine("/:.");
                var vh = server.GetSingleApp();

                // Redo in new domain
                vh.CreateHost(server, source);
                var xsp = (Xsp)vh.AppHost.Domain.CreateInstanceAndUnwrap(
                    typeof(Xsp).Assembly.FullName, typeof(Xsp).FullName);
                source.Dispose();

                xsp.Initialize(vh.AppHost, port, vpath, ppath);
                return xsp;
            }
        }
    }

    public class Xsp : MarshalByRefObject, IWebHost
    {
        private ApplicationServer server;

        public Xsp()
        {
            App.InitializeAppDomainAndLogger("_0");
        }

        public void Initialize(object app, int port, string vpath, string ppath)
        {
            var source = new XSPWebSource(IPAddress.Any, port, true);
            server = new ApplicationServer(source);

            server.Verbose = false;
            server.SingleApplication = true;
            server.AddApplicationsFromCommandLine("/:.");

            server.AppHost = app as IApplicationHost;
        }

        public void Start()
        {
            if (server != null)
            {
                server.Start(true);
                Log.WriteInfo("Http server started, port={0}, dir={1}", server.Port, Directory.GetCurrentDirectory());
            }
            else
            {
                throw new NullReferenceException("Cannot start xsp since ApplicationServer is null");
            }
        }

        public void Stop()
        {
            if (server != null)
            {
                server.Stop();
                Log.WriteInfo("Http server stopped");
            }
            else
            {
                throw new NullReferenceException("Cannot stop xsp since ApplicationServer is null");
            }
        }
    }
}
